
#include "OGLCamera.h"
#include "Main.h"
#include "vector3f.h"


OGLCamera::OGLCamera()
{
	mEyePosition.set(0.0f,0.0f,0.0f);
	mLook.set(0.0f,0.0f,1.0f);
	mUp.set(0.0f,1.0f,0.0f);
	mRight.set(1.0f,0.0f,0.0f);

	mCamSpeed = 10;
}

void OGLCamera::UpdateCameraInput(POINT *inPoint, bool * inKeys, float deltaTime)
{
	matrix4x4f matRotation;
	mMouseCurPosition.x = inPoint->x;
	mMouseCurPosition.y = inPoint->y;


	if(mIsMouseMoving)
	{
		mIsMouseMoving = false;
		int inXDiff = mMouseCurPosition.x - mMouseLastPosition.x;
		int inYDiff = 0;//mMouseCurPosition.y - mMouseLastPosition.y;

		if(inYDiff != 0)
		{
			matRotation.rotate(-(float)inYDiff/3.0f,mRight);
			matRotation.transformVector(&mLook);
			matRotation.transformVector(&mUp);
		}

		 if( inXDiff != 0 )
        {
            matRotation.rotate(-(float)inXDiff / 2.0f, vector3f(0.0f, 1.0f, 0.0f) );
            matRotation.transformVector( &mLook );
            matRotation.transformVector( &mUp );
        }

		 mMouseLastPosition = mMouseCurPosition;
	}

		 vector3f tempLook = mLook;
		 vector3f tempRight = mRight;

		 if(inKeys['W'])
		 {
			 mEyePosition += tempLook * deltaTime * mCamSpeed;
		 }

		 if(inKeys['S'])
		 {
			 mEyePosition -= tempLook * deltaTime * mCamSpeed;
		 }

		  if(inKeys['A'])
		 {
			 mEyePosition -= tempRight * deltaTime * mCamSpeed;
		 }

		 if(inKeys['D'])
		 {
			 mEyePosition += tempRight * deltaTime * mCamSpeed;
		 }
   
}


//-----------------------------------------------------------------------------
// Name : updateViewMatrix() 
// Desc : Builds a view matrix suitable for OpenGL.
//
// Here's what the final view matrix should look like:
//
//  |  rx   ry   rz  -(r.e) |
//  |  ux   uy   uz  -(u.e) |
//  | -lx  -ly  -lz   (l.e) |
//  |   0    0    0     1   |
//
// Where r = Right vector
//       u = Up vector
//       l = Look vector
//       e = Eye position in world space
//       . = Dot-product operation
//
//-----------------------------------------------------------------------------
void OGLCamera::UpdateViewMatrix(void)
{
	matrix4x4f view;

	view.identity();

	mLook.normalize();

	mRight = vector3f::crossProduct(mLook, mUp);
	mRight.normalize();

	mUp =  vector3f::crossProduct(mRight, mLook);
	mUp.normalize();

	view.m[0] =  mRight.x;
	view.m[1] =  mUp.x;
	view.m[2] = -mLook.x;
	view.m[3] =  0.0f;

	view.m[4] =  mRight.y;
	view.m[5] =  mUp.y;
	view.m[6] = -mLook.y;
	view.m[7] =  0.0f;

	view.m[8]  =  mRight.z;
	view.m[9]  =  mUp.z;
	view.m[10] = -mLook.z;
	view.m[11] =  0.0f;

	view.m[12] = - vector3f::dotProduct(mRight, mEyePosition);
	view.m[13] = - vector3f::dotProduct(mUp, mEyePosition);
	view.m[14] =   vector3f::dotProduct(mLook, mEyePosition);
	view.m[15] =  1.0f;

	glMultMatrixf( view.m );

	
}

